﻿using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Tw.Trains.Domain;

namespace Tw.Trains
{
    /// <summary> 列车线路管理 </summary>
    public class TrainsManager
    {
        private readonly TrainGraph _trainGraph;

        public TrainsManager(string graphs)
        {
            _trainGraph = new TrainGraph();
            _trainGraph.AddTrains(graphs);
        }

        /// <summary> 路线距离 </summary>
        /// <param name="route"></param>
        /// <returns></returns>
        public int RouteDistance(string route)
        {
            var isMatch = Regex.IsMatch(route, "([a-z])(-[a-z])+", RegexOptions.IgnoreCase);
            if (!isMatch)
                return -1;
            var stations = route.Split(new[] { "-" }, StringSplitOptions.RemoveEmptyEntries);
            var distance = 0;
            for (var i = 0; i < stations.Length - 1; i++)
            {
                var d = _trainGraph.Distance(new Station(stations[i]), new Station(stations[i + 1]));
                if (d < 0)
                    return -1;
                distance += d;
            }
            return distance;
        }

        /// <summary> 出行线路 </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public List<TripNode> Trips(Station start, Station end, TripCondition condition)
        {
            return _trainGraph.Trips(start, end, condition);
        }

        /// <summary> 出行线路 </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public List<TripNode> Trips(string start, string end, TripCondition condition)
        {
            return Trips(new Station(start), new Station(end), condition);
        }

        /// <summary> 最短距离线路 </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public TripNode BestTrip(Station start, Station end)
        {
            return _trainGraph.BestTrip(start, end);
        }

        /// <summary>
        /// 最短距离线路
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public TripNode BestTrip(string start, string end)
        {
            return _trainGraph.BestTrip(new Station(start), new Station(end));
        }
    }
}
